package danny.hoi.web.controller.base;

import danny.hoi.domain.export.admin.Module;
import danny.hoi.domain.export.admin.ModuleExample;
import danny.hoi.domain.export.system.User;
import danny.hoi.service.export.admin.ModuleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
public class LoginController extends BaseController {
    @Autowired
    private ModuleService moduleService;

    //登录
    @RequestMapping("/login")
    public String login(String email, String password) {
        if (session.getAttribute("loginUser") != null) {
            return "home/main";
        }
        if (StringUtils.isEmpty(email) || StringUtils.isEmpty(password)) {
            request.setAttribute("error", "账号或密码不能为空");
            return "forward:/login.jsp";
        }
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(new UsernamePasswordToken(email, password));
            //登陆验证通过
            User user = (User) subject.getPrincipal();
            session.setAttribute("loginUser", user);
            //根据用户等级查询当前用户的所有模块
            ModuleExample moduleExample = new ModuleExample();
            ModuleExample.Criteria criteria = moduleExample.createCriteria();
            List<Module> modules = null;
            if (user.getDegree() == 0) {
                //saas管理员
                criteria.andBelongEqualTo("0");
                modules = moduleService.findAll(moduleExample);
            } else if (user.getDegree() == 1) {
                //企业管理员
                criteria.andBelongEqualTo("1");
                modules = moduleService.findAll(moduleExample);
            } else {
                //普通员工
                modules = moduleService.findModuleByUserId(user.getUserId());
            }
            session.setAttribute("modules", modules);
            return "home/main";
        } catch (AuthenticationException e) {
            e.printStackTrace();
            request.setAttribute("error", "账号或密码不正确");
            return "forward:/login.jsp";
        }
    }

    //iframe访问home
    @RequestMapping("/home")
    public String home() {
        return "home/home";
    }

    @RequestMapping("/logout")
    public String logout() {
        session.removeAttribute("loginUser");
        session.invalidate();
        return "forward:/login.jsp";
    }
}
